# coding=utf-8
__author__ = 'liubin'

from tornado.web import asynchronous
from sqlalchemy import or_, desc
from sqlalchemy.orm import contains_eager
from tornado_json.requesthandlers import APIHandler
from project.tools import HandlerMixin, unblock, to_json
from project.models import User, Role


class UserHandler(HandlerMixin, APIHandler):
    """
    用户API
    """
    __url_names__ = []


    #@asynchronous
    def check_userId_not_exist(self, userId):
        """
        检查用户ID存在
        """
        user = self.db_conn.query(User).filter_by(userId=userId, isDeleted=False).first()
        if user:
            self.error(u'指定用户ID已被使用')
            return False
        return True

    #@asynchronous
    def check_id_exist(self, id):
        """
        检查用户存在
        """
        user = self.db_conn.query(User).filter_by(id=id, isDeleted=False).first()
        if not user:
            self.error(u'指定用户不存在')
        return user

class SingleHandler(UserHandler):
    """
    单用户
    """
    __urls__ = [r"/api/user/(?P<id>[a-zA-Z0-9_]+)/?"]

    @unblock
    def get(self, id):
        """
        获取单条记录
        :param id:
        :return:
        """
        print(id)
        # 取单条数据
        #user = self.db_conn.query(User).filter_by(id=id, isDeleted=False).first()
        user = self.check_id_exist(id)
        if user:
            self.success(to_json(user))

    @unblock
    def put(self, id):
        """
        更新单条记录
        """
        #user = self.db_conn.query(User).filter_by(id=id, isDeleted=False).first()
        user = self.check_id_exist(id)
        if user:
            data = self.json_args
            user.name = data['name']
            user.roleId = data['roleId']
            self.db_conn.commit()
            self.success(None)

    @unblock
    def delete(self, id):
        """
        删除单条记录
        """
        #user = self.db_conn.query(User).filter_by(id=id, isDeleted=False).first()
        user = self.check_id_exist(id)
        if user:
            # 删除
            #self.db_conn.delete(user)
            #提交
            user.isDeleted = True
            self.db_conn.commit()
            self.success(None)

class PwdHandler(UserHandler):
    """
    密码相关
    """
    __urls__ = [r'/api/user/(?P<id>[a-zA-Z0-9_]+)/modifyPwd/?']

    @unblock
    def put(self, id):
        """
        修改密码
        """
        #user = self.db_conn.query(User).filter_by(id=id, isDeleted=False).first()
        user = self.check_id_exist(id)
        if user:
            data = self.json_args
            #user.password = data['password']
            user.setEncryptPwd(data.get('password'))
            self.db_conn.commit()
            self.success(None)

class ListHandler(UserHandler):
    """
    用户列表
    """
    __urls__ = [r'/api/user/?']

    @unblock
    def get(self):
        """
        获取用户列表
        :return:
        """
        # 无关字段, 原样返回
        draw = self.get_query_argument('draw', 0)
        # 分页大小
        size = int(self.get_query_argument('size', 0))
        # 第几项开始
        start = int(self.get_query_argument('start', 0))
        # 查询字段
        query = self.get_query_argument('query', '')
        # 排序字段
        order = self.get_query_argument('order', '')
        # 正序或倒叙
        sort = self.get_query_argument('dir', '')
        end = start + size
        users = self.db_conn.query(User).join(User.role).options(
            contains_eager(User.role)).filter(User.isDeleted == False)
        if query:
            users = users.filter(
                or_(
                    User.userId.like('%' + query + '%'),
                    User.name.like('%' + query + '%')
                )
            )
        if order:
            if sort == 'desc':
                users = users.order_by(desc(getattr(User, order)))
            else:
                users = users.order_by(getattr(User, order))
        # 总件数
        total = users.count()
        if end:
             users = users.slice(start, end)
        #print(users)
        # print(users)
        # print(len(users))
        users = users.all()
        self.success(to_json(users), draw=draw, total=total)

    @unblock
    def post(self):
        print(self.json_args)
        # 初始化用户
        user = User(self.json_args)
        user.set_encrypt_pwd(user.password)
        # 用户ID检查
        if self.check_userId_not_exist(user.userId):

            self.db_conn.add(user)
            self.db_conn.commit()
            self.success(None)


